package com.adingxiong.springsecurityoauth2.oauth.config;

import com.adingxiong.springsecurityoauth2.oauth.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

/**
 * @ClassName MyAuthorizationServerConfigurer
 * @Description     客户端从认证服务器获取令牌的时候，必须使用client_id为 adingxiong，client_secret为123456的标识来获取；
                 * 该client_id支持 password、authorization_code 模式获取令牌，并且可以通过refresh_token来获取新的令牌；
                 * 在获取client_id为adingxiong的令牌的时候，scope需指定为all，否则将获取失败；
                 * 配置了redirectUris，指定了获取code时的重定向地址；
 * @Author xiongchao
 * @Date 2020/10/29 14:03
 **/
@Configuration
@EnableAuthorizationServer
/**
 * // EnableAuthorizationServer 来开启认证服务器功能。
 */
public class MyAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyUserDetailService userDetailService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailService);
    }


    /**
     * 客户端认证方式   credentials 配置之后 不需要用户名 密码即可获取token
     * @param clients
     * @throws Exception
     */

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("kiki")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("password","refresh_token","authorization_code","client_credentials")
                .autoApprove(true)
                .scopes("all")
                .redirectUris("http://localhost:8001/getCode");
    }
}
